package com.ykq.sso.realm;


import com.ykq.pojo.entity.User;
import com.ykq.sso.feign.SystemFeign;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: qy150-ssm-shiro
 * @description:
 * @author: 闫克起2
 * @create: 2022-07-15 10:39
 **/
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private SystemFeign systemFeign;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        return null;

    }

    //认证功能
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        User user = systemFeign.findByName(username);
        if (user != null) {

            //根据用户id查询该用户具有的权限。
            List<String> permissions = systemFeign.findByUserId(user.getId());

            ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());

            Map<String,Object> map=new HashMap<>();
            map.put("user",user);
            map.put("permissions",permissions);
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(map, user.getPassword(), credentialsSalt, this.getName());
            return info;
        }
        return null;
    }

    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("123456", "8e1e", 1024);
        Md5Hash md5Hash2 = new Md5Hash("123456", "test", 1024);
        System.out.println(md5Hash);
        System.out.println(md5Hash2);
    }
}
